#include "clientstableview.h"
#include "QTableView"
#include "QVBoxLayout"
#include "db/clientsdao.h"
#include "QLabel"
#include "QSqlTableModel"
#include "db/databaseconn.h"
#include "dialogs/cameradialog.h"


ClientsTableView::ClientsTableView(QWidget *parent) : QWidget(parent){

    tableView= new QTableView(this);

    QVBoxLayout *layout = new QVBoxLayout;
    QLabel *label = new QLabel(this);
    label->setText("Clients List");
    layout->addWidget(label);
    layout->addWidget(tableView);
    QHBoxLayout *controlsLayout = new QHBoxLayout;
    //newClientButton = new QPushButton(this);
    newClientButton = new QPushButton(this);
    newClientButton->setText("New Client");

    editClientButton = new QPushButton(this);
    editClientButton->setText("Edit Client");

    deleteClientButton = new QPushButton(this);
    deleteClientButton->setText("Delete Client");

    editClientButton->setDisabled(true);
    deleteClientButton->setDisabled(true);

    //QPushbutton *deleteClientButton;
    //QPushbutton *editClientButton;

    controlsLayout->addWidget(newClientButton);
    controlsLayout->addWidget(editClientButton);
    controlsLayout->addWidget(deleteClientButton);

    layout->addLayout(controlsLayout);

    setLayout(layout);
    resize(500, 400);

    qDebug("clientsTableView Loaded");

    DatabaseConn *conn = new DatabaseConn(this);

    conn->openConnection();

    model = new QSqlTableModel(this,conn->getDataBase());

    model->setTable( "clients" );

    //remove profilepic column
    model->removeColumn(5);

    model->setHeaderData(0, Qt::Horizontal, tr("Id"));
    model->setHeaderData(1, Qt::Horizontal, tr("Name"));
    model->setHeaderData(2, Qt::Horizontal, tr("LastName"));
    model->setHeaderData(3, Qt::Horizontal, tr("Address"));
    model->setHeaderData(4, Qt::Horizontal, tr("Inscription Date"));

    model->select();
    tableView->setModel(model);
    tableView->setSelectionBehavior(QAbstractItemView::SelectRows);

    connect(tableView,SIGNAL(clicked(QModelIndex)),this,SLOT(selectRow(QModelIndex)));
    connect(editClientButton,SIGNAL(clicked()),this,SLOT(showDialog()));

    tableView->resizeColumnsToContents();

    conn->closeConnection();

}

void ClientsTableView::selectRow(QModelIndex index){

    qDebug("row selected");
    qDebug("row number=%d",index.row());
    //QPoint point = new QPoint(index.row(),0);

    QModelIndex indexId = tableView->indexAt(QPoint(index.row(),0));
    QVariant var = model->data(indexId);

    rowSelected = var.toInt();

    qDebug(var.toString().toLatin1());

    editClientButton->setDisabled(false);
    deleteClientButton->setDisabled(false);

}

void ClientsTableView::showDialog(){
    //CameraDialog *dialog = new CameraDialog();
    //dialog->show();
    emit editClient(rowSelected);
}


ClientsTableView::~ClientsTableView(){

}




